package src.com.qf.filter;

import src.com.qf.entity.User;
import src.com.qf.service.UserService;
import src.com.qf.service.impl.UserServiceImpl;
import src.com.qf.utils.Base64Util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AutoLoginFilter",value = "/login.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Cookie[] cookies = request.getCookies();
        if (cookies !=null){
            for (Cookie c : cookies) {
                if ("autoLogin".equals(c.getName())){
                    String value = c.getValue();//加密后的字符串
                    //解密
                    String decode = Base64Util.decode(value);
                    String[] split = decode.split(":");
                    String username = split[0];
                    String password = split[1];

                    UserService userService = new UserServiceImpl();
                    User login = userService.login(username,password);

                    if (login == null){
                        System.out.println("登录失败");
                        chain.doFilter(req, resp);
                    }else {
                        System.out.println("登陆成功");
                        request.getSession().setAttribute("loginUser",login);
                        response.sendRedirect(request.getContextPath()+"/good?action=getGoodsListByTypeId");
                    }
                }else {
                    chain.doFilter(req, resp);
                }
            }
        }else {
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
